<template>
  <div class="formulaManage-page">
    <div class="search-field">
      <el-form :model="searchForm" inline>
        <el-form-item label="类型" prop="categoryId">
          <el-select
            style="width: 220px"
            v-model="searchForm.categoryId"
            placeholder="选择配方分类"
          >
            <el-option
              v-for="option in formulaCategoryList"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="编码" prop="number">
          <el-input
            placeholder="请输入编码"
            v-model="searchForm.number"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input
            placeholder="请输入名称"
            v-model="searchForm.name"
            autocomplete="off"
          />
        </el-form-item>

        <el-form-item label="状态" prop="enabled">
          <el-select
            style="width: 220px"
            v-model="searchForm.enabled"
            placeholder="选择状态"
          >
            <el-option
              v-for="option in statusOptions"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <div>
            <el-button type="primary" @click="startSearch"> 查询 </el-button>
            <el-button @click="startClear"> 重置 </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-pagination-content">
      <div class="btns-fun-field">
        <!-- v-if="userPermission.addUserPerm" -->
        <el-button
          type="primary"
          @click.prevent="showAddEditDialog"
          :icon="Plus"
        >
          新增配方管理
        </el-button>
      </div>
      <div class="table-field">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          v-loading="tableLoading"
        >
          <el-table-column prop="number" label="配方编码" width="120" />
          <el-table-column prop="name" label="配方名称" width="160" />
          <el-table-column prop="categoryName" label="配方类型" width="140" />
          <el-table-column prop="enabled" label="状态" width="80">
            <template #default="scope">
              <el-tag
                :type="scope.row.enabled == 1 ? 'danger' : 'success'"
                disable-transitions
              >
                {{ scope.row.enabled == 1 ? '禁用' : '启用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" min-width="220px" fixed="right">
            <template #default="scope">
              <!-- v-if="rolePermission.editRolePerm" -->
              <el-button
                type="primary"
                size="small"
                @click.prevent="copyNewFormula(scope.row, 2)"
                >复制配方</el-button
              >
              <el-button
                type="primary"
                size="small"
                @click.prevent="showDetailDialog(scope.row, 2)"
                >详情</el-button
              >
              <el-button
                type="success"
                size="small"
                @click.prevent="showAddEditDialog(scope.row, 2)"
                >编辑</el-button
              >
              <!-- v-if="rolePermission.removeRolePerm" -->
              <el-button
                type="danger"
                size="small"
                @click.prevent="showRemoveDialog(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-field">
        <el-pagination
          v-model:current-page="formData.pageIndex"
          v-model:page-size="formData.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="formData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <FormulaManageAddUpdate
      v-if="addUpdateRef.visible"
      v-model="addUpdateRef"
    ></FormulaManageAddUpdate>
    <FormulaManageRemove
      v-if="removeRef.visible"
      v-model="removeRef"
    ></FormulaManageRemove>
    <FormulaDetail v-if="detailRef.visible" v-model="detailRef"></FormulaDetail>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import {
  getFormulamanageAllList,
  getFormulamanagePagination,
} from '@/api/fms-formula-manage.api'
import { getMaterialConfigAllList } from '@/api/fms-material-config.api'
import { getSpecificationConfigAllList } from '@/api/fms-specification-config.api'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
// import { useUserPermission } from "@/utils/permission.utils";
import FormulaManageRemove from './FormulaManageRemove.vue'
import FormulaManageAddUpdate from './FormulaManageAddUpdate.vue'
import { getRecipecategoryAllList } from '@/api/fms-recipe-category.api'
import { getCanUseCode } from '@/api/fms-code-dict.api'
import { statusOptions } from '@/utils/common.utils'
import FormulaDetail from './FormulaDetail.vue'
import {
  addFormulamanage,
  updateFormulamanage,
} from '@/api/fms-formula-manage.api'

const requestCanUseCode = () => {
  getCanUseCode({ type: 401 })
    .then((res: any) => {
      console.log('getCanUseCode: ', res)
      addUpdateRef.form.number = res
    })
    .catch((err) => {
      ElMessage.error(err.msg)
    })
}
// const userPermission = useUserPermission();

/****
 * =============== 拷贝新的配方 =====================
 */
const copyNewFormula = async (item: any) => {
  try {
    let value = await getCanUseCode({ type: 401 })
    item.id = null
    item.number = value

    //处理完所有的id
    let productRules = item.productRules || []
    let productSpecGroups = item.productSpecGroups || []
    let productSteps = item.productSteps || []
    productRules = productRules.map((item: any) => {
      item.id = null
      return item
    })
    productSpecGroups = productSpecGroups.map((item: any) => {
      item.id = null
      return item
    })
    productSteps = productSteps.map((item: any) => {
      item.id = null
      return item
    })
    item.productRules = productRules
    item.productSpecGroups = productSpecGroups
    item.productSteps = productSteps

    addFormulamanage(item)
      .then((res) => {
        //to do
        // cancel()
        ElMessage({
          message: '新增成功',
          type: 'success',
        })
        getDataList()
      })
      .catch((err) => {
        ElMessage({
          message: err.msg || err,
          type: 'error',
        })
      })
  } catch (err: any) {
    ElMessage.error(err.msg)
  }
}

/****
 * =============== 展示详情相关操作 =====================
 */
const detailRef = reactive({
  visible: false,
  title: `配方管理详情`,
  curSelectRow: {},
  form: {},
  refreshDataList: () => {
    getDataList()
  },
})

const showDetailDialog = (item: any) => {
  detailRef.visible = true
  detailRef.curSelectRow = item
  detailRef.form = item
}

/****
 * =============== 新增、修改相关操作 =====================
 */
const addUpdateRef = reactive({
  visible: false,
  disabled: false,
  title: `配方管理`,
  curSelectRow: {},
  formulaCategoryList: [],
  materialConfigList: [],
  specificationConfigAllList: [],
  form: {
    number: '',
  },
  rules: {},
  refreshDataList: () => {
    getDataList()
  },
})

const showAddEditDialog = (item: any, type: number) => {
  //新增 配方管理
  if (item.target) {
    let form = {
      id: null,
      //名称
      name: '',
      //编号
      number: '',
      //配方类型
      categoryId: '',
      //外编号
      orNumber: '',
      //外编号分类
      menuCategory: '',

      isBaseline: '',
      enabled: 0 + '',
      productSteps: [],
      specificationIds: [],
      productSpecGroups: [],
      productRules: [],
    }
    addUpdateRef.visible = true
    addUpdateRef.disabled = false
    addUpdateRef.form = form
    requestCanUseCode()
    return
  }

  let form = {
    id: item.id,
    name: item.name,
    number: item.number,
    orNumber: item.orNumber,
    orCategoryId: item.orCategoryId,
    categoryId: item.categoryId,
    remark: item.remark,
    isBaseline: true,
    enabled: item.enabled + '',
    productSteps: item.productSteps || [],
    specificationIds: item.specificationIds || [],
    productSpecGroups: item.productSpecGroups,
    productRules: item.productRules,
  }
  addUpdateRef.visible = true
  addUpdateRef.disabled = true
  addUpdateRef.form = form
}

/****
 * =============== 删除操作 =====================
 */
const removeRef = reactive({
  visible: false,
  title: '配方管理',
  curSelectRow: {},
  refreshDataList: () => {
    getDataList()
  },
})
const showRemoveDialog = (item: any) => {
  removeRef.visible = true
  removeRef.curSelectRow = item
}

/****
 * =============== 搜索、表格、分页 =====================
 */
const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

const searchForm = ref({
  name: '',
  number: '',
  categoryNumber: '',
  isBaseline: '',
  updateTime: '',
  enabled: '',
  costPrice: '',
  proposalPrice: '',
  alias: '',
  filePath: '',
  fileCreateTime: '',
  srcProductId: '',
  extractMaterialNumber: '',
  relatedMaterialNumber: '',
  extractMaterialName: '',
})

const tableLoading = ref(false)
const tableData = ref([])
/***
 * 开始搜索
 */
const startSearch = () => {
  formData.pageIndex = 1
  getDataList()
}

/***
 * 重置搜索条件
 */
const startClear = () => {
  formData.pageIndex = 1
  let value = searchForm.value
  Object.keys(value).forEach((key) => {
    ;(value as any)[key] = ''
  })
  getDataList()
}

const handleSizeChange = (value: number) => {
  formData.pageSize = value
  getDataList()
}

const handleCurrentChange = (value: number) => {
  formData.pageIndex = value
  getDataList()
}

const getDataList = () => {
  let searchCondition: any = {}

  let name = searchForm.value.name
  if (name) {
    searchCondition.name = name
  }
  let number = searchForm.value.number
  if (number) {
    searchCondition.number = number
  }
  let categoryId = searchForm.value.categoryId
  if (categoryId) {
    searchCondition.categoryId = categoryId
  }

  let enabled = searchForm.value.enabled
  if (enabled) {
    searchCondition.enabled = enabled
  }

  tableLoading.value = true
  getFormulamanagePagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
    ...searchCondition,
  })
    .then(function (res: any) {
      tableLoading.value = false
      console.log(res)

      let list = res.list || []
      list = list.map((item: any) => {
        let specList = item.productSpecGroups || []
        item.productSpecGroups = specList.map((spec: any) => {
          let list = spec.specList || []
          list = list.map((row) => {
            row.selected = true //row.defaultSelected ? true : false;
            return row
          })
          spec.list = list
          return spec
        })
        item.specificationIds = specList.map((spec: any) => spec.number)
        return item
      })

      tableData.value = list
      formData.total = Number(res.total)
    })
    .catch((error) => {
      console.log(error)
      tableLoading.value = false
    })
}

const formulaCategoryList = ref([])
const requestRecipecategoryAllList = () => {
  getRecipecategoryAllList({})
    .then((res: any) => {
      formulaCategoryList.value = res || []
      addUpdateRef.formulaCategoryList = formulaCategoryList.value
    })
    .catch((err) => {
      console.log(err)
    })
}

const materialConfigList = ref([])
const requestMaterialConfigAllList = () => {
  getMaterialConfigAllList({})
    .then((res: any) => {
      materialConfigList.value = res || []
      addUpdateRef.materialConfigList = materialConfigList.value
    })
    .catch((err) => {
      console.log(err)
    })
}

const specificationConfigAllList = ref([])
const requestSpecificationConfigAllList = () => {
  getSpecificationConfigAllList({})
    .then((res: any) => {
      specificationConfigAllList.value = res || []
      addUpdateRef.specificationConfigAllList = specificationConfigAllList.value
    })
    .catch((err) => {
      console.log(err)
    })
}

onMounted(() => {
  requestRecipecategoryAllList()
  requestMaterialConfigAllList()
  requestSpecificationConfigAllList()
  getDataList()
})
</script>
<style lang="scss" scoped>
.formulaManage-page {
  height: 100%;
}

.btns-fun-field {
  margin-bottom: 20px;
}

.pagination-field {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.btn-inner {
  display: flex;
  justify-content: center;
  color: #fff;
}

.tag-field {
  .el-tag {
    margin-right: 5px;
    &:last-child {
      margin-right: 0;
    }
  }
}

.search-field {
  margin-bottom: 12px;
  background: #fff;
  padding: 20px 20px 0px 20px;
  border-radius: 8px;
}

.formulaManage-page-content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}
</style>
